package com.mgm.advertisement.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mgm.advertisement.service.AdvertisementService;
import com.mgm.constant.GobalConstant;
import com.mgm.dao.AdvertisementMapper;
import com.mgm.dao.AdvertiserMapper;
import com.mgm.page.DataGrid;
import com.mgm.pojo.Advertisement;
import com.mgm.pojo.AdvertisementExample;
import com.mgm.pojo.Advertiser;
import com.mgm.pojo.AdvertisementExample.Criteria;
import com.mgm.result.IMessage;
import com.mgm.result.IResult;
import com.mgm.utils.NumberArithmeticUtils;
import com.mgm.utils.RandomCodeUtils;

/**
 * 
 * @ClassName: AdvertisementServiceImpl 
 * @Description: TODO(...) 
 * @author Andy Zhang
 * @date 2018年6月28日 下午8:54:33 
 *
 */
@Service
public class AdvertisementServiceImpl implements AdvertisementService {
	
	/** 默认广告主溢价等于100 */
	protected final Integer PREMIUM = 100; 

	@Autowired
	private AdvertisementMapper advertisementMapper;
	@Autowired
	private AdvertiserMapper advertiserMapper;
	
	@Override
	public IMessage addAdvertisement(Advertisement advertisement) {
		String offerid = System.currentTimeMillis()+RandomCodeUtils.radomIntNumeric(10000)+"";
		advertisement.setOfferId(offerid);
		advertisement.setP1(offerid);
		advertisementMapper.insertSelective(advertisement);
		
		return IMessage.success();
	}

	@Override
	public IMessage deleteAdvertisement(Advertisement advertisement) {
		advertisementMapper.deleteByPrimaryKey(advertisement.getId());
		return IMessage.success();
	}
	
	@Override
	public IMessage deleteAdvertisement(Integer adId, Integer id) {
		Advertisement adsment = advertisementMapper.selectByPrimaryKey(id);
		if(adsment.getAdv_id() != adId) {
			return IMessage.error("广告主与广告不匹配,不能删除");
		}
		advertisementMapper.deleteByPrimaryKey(id);
		return IMessage.success();
	}

	@Override
	public IMessage deleteById(List<Integer> ids) {
		for (Integer id : ids) {
			advertisementMapper.deleteByPrimaryKey(id);
		}
		return IMessage.success();
	}

	@Override
	public IMessage updateAdvertisement(Advertisement advertisement) {
		Advertisement adsment = advertisementMapper.selectByPrimaryKey(advertisement.getId());
		if(adsment.getAdv_id() != advertisement.getAdv_id()) {
			return IMessage.error("广告主与广告不匹配");
		}
		advertisementMapper.updateByPrimaryKeySelective(advertisement);
		return IMessage.success();
	}

	@Override
	public IMessage isEnabled(Integer id, Boolean enabled) {
		Advertisement record = new Advertisement();
		record.setId(id);
		record.setEnabled(enabled);
		advertisementMapper.updateByPrimaryKeySelective(record);
		return IMessage.success();
	}
	
	@Override
	public IMessage modifyPremium(Integer id, Integer premium) {
		Advertisement ad = advertisementMapper.selectByPrimaryKey(id);
		Advertisement record = new Advertisement();
		record.setId(id);
		record.setPremium(premium);
		if(premium != null) { //如果溢价不为空，设置溢价后单价
			BigDecimal premiumPercent = NumberArithmeticUtils.safeDivide(premium, GobalConstant.PERCENT); //溢价/100
			record.setPremium_price(NumberArithmeticUtils.safeMultiply(premiumPercent, ad.getPay_price())); //溢价后单价
		}
		advertisementMapper.updateByPrimaryKeySelective(record);
		return IMessage.success();
	}
	
	@Override
	public IMessage modifyInitialPremium(Integer id) {
		advertisementMapper.updatePremiumClean(id);
		return IMessage.success();
	}
	
	@Override
	public IMessage modifyCaps(Integer id, BigDecimal totalCap, BigDecimal dailyCap) {
		if(totalCap==null || dailyCap==null) {
			return IMessage.error("Cap 不能为NULL");
		}
		Advertisement record = new Advertisement();
		record.setId(id);
		record.setPayout_cap(totalCap);
		record.setDaily_payout_cap(dailyCap);
		advertisementMapper.updateByPrimaryKeySelective(record);
		return IMessage.success();
	}
	
	@Override
	public IMessage modifyInitialCaps(Integer id) {
		Advertisement adment = advertisementMapper.selectByPrimaryKey(id);
		adment.setPayout_cap(null); //要求还原为null值
		adment.setDaily_payout_cap(null); //要求还原为null值
		advertisementMapper.updateByPrimaryKey(adment);
		return IMessage.success();
	}

	@Override
	public Advertisement selectById(Integer id) {
		return advertisementMapper.selectByPrimaryKey(id);
	}

	@Override
	public List<Advertisement> findAllByEnabled() {
		AdvertisementExample example = new AdvertisementExample();
		Criteria criteria = example.createCriteria();
		criteria.andEnabledEqualTo((byte) 1);
		return advertisementMapper.selectByExample(example);
	}

	@Override
	public DataGrid findAll(Map<String, String> param, Integer pageNum, Integer pageSize) {
		//查询
		AdvertisementExample example = new AdvertisementExample();
		//分页处理
		PageHelper.startPage(pageNum, pageSize);
		//创建条件
		Criteria criteria = example.createCriteria();
		String advId = param.get("advId");
		String offerId = param.get("offerId");
		String offerName = param.get("offerName");
		String pkgName = param.get("pkgName");
		String country = param.get("country");
		String enabled = param.get("enabled");
		
		if(!StringUtils.isEmpty(advId)) {
			String[] advIds = advId.split(",");
			List<Integer> advidsList = new ArrayList<>();
			for (String advid : advIds) {
				advidsList.add(Integer.valueOf(advid));
			}
			criteria.andAdv_idIn(advidsList);
		}
		if(!StringUtils.isEmpty(offerId)) {
			criteria.andOfferIdLike("%" + offerId + "%");
		}
		if(!StringUtils.isEmpty(offerName)) {
			criteria.andOfferNameLike("%" + offerName + "%");
		}
		if(!StringUtils.isEmpty(pkgName)) {
			criteria.andPkgnameLike("%" + pkgName + "%");
		}
		if(!StringUtils.isEmpty(country)) {
			criteria.andCountriesLike("%" + country+ "%");
		}
		if(!StringUtils.isEmpty(enabled)) {
			criteria.andEnabledEqualTo(enabled.equals("true") ? (byte)1 : (byte) 0);
		}
		
		List<Advertisement> list = advertisementMapper.selectByExample(example);
		list = convertList(list);
		
		//创建一个返回值对象
		DataGrid dataGrid = new DataGrid();
		dataGrid.setItems(list);
		//获取PageInfo相关信息
		PageInfo<Advertisement> pageInfo = new PageInfo<>(list);
		dataGrid.setTotal_count(pageInfo.getTotal()); //总记录数
		dataGrid.setPage_count(pageInfo.getPages()); // 总页数
		dataGrid.setPage_index(pageInfo.getPageNum()); // 当前页
		
		return dataGrid;
	}

	@Override
	public List<Advertisement> findByName(String name) {
		AdvertisementExample example = new AdvertisementExample();
		Criteria criteria = example.createCriteria();
		criteria.andOfferNameEqualTo(name);
		return advertisementMapper.selectByExample(example);
	}

	@Override
	public IResult<Advertisement> selectByKeys(Integer adId, Integer id) {
		AdvertisementExample example = new AdvertisementExample();
		Criteria criteria = example.createCriteria();
		criteria.andAdv_idEqualTo(adId);
		criteria.andIdEqualTo(id);
		List<Advertisement> list = advertisementMapper.selectByExample(example);
		if(list!=null) {
			Advertisement adment = list.get(0);
			Map<Integer, Advertiser> map = advertiserMapper.selectAllMap();
			Advertiser ader = map.get(adment.getAdv_id());
			adment.setAderName(ader.getName());
			adment.setAderType(ader.getAdvType());
			return IResult.success(adment);
		}
		return IResult.success();
	}

	@Override
	public int insertBatch(List<Advertisement> list) {
		return advertisementMapper.insertBatch(list);
	}

	@Override
	public int updateBatch(List<Advertisement> list) {
		return advertisementMapper.updateBatch(list);
	}
	
	@Override
	public List<Advertisement> findByAdvIdAndOldOfferId(Integer advId, List<String> oldOfferId) {
		AdvertisementExample example = new AdvertisementExample();
		Criteria criteria = example.createCriteria();
		criteria.andAdv_idEqualTo(advId);
		criteria.andP1In(oldOfferId);
		List<Advertisement> list = advertisementMapper.selectByExample(example);
		return list;
	}

	@Override
	public Advertisement findByOfferId(String offerId) {
		AdvertisementExample example = new AdvertisementExample();
		Criteria criteria = example.createCriteria();
		criteria.andOfferIdEqualTo(offerId);
		List<Advertisement> list = advertisementMapper.selectByExample(example);
		if(CollectionUtils.isEmpty(list)) {
			return null;
		}
		return list.get(0);
	}

	@Override
	public int updateOfferByAdvIdAndEnabledAndNotInOfferIds(Integer advId, List<String> oldOfferIds) {
		AdvertisementExample example = new AdvertisementExample();
		Criteria criteria = example.createCriteria();
		criteria.andAdv_idEqualTo(advId);
		criteria.andP1NotIn(oldOfferIds);
		criteria.andEnabledEqualTo((byte)1);
		List<Advertisement> list = advertisementMapper.selectByExample(example);
		Date curTime = new Date();
		if(!CollectionUtils.isEmpty(list)) {
			for (Advertisement advertisement : list) {
				advertisement.setEnabled(false);
				advertisement.setEnd_at(curTime);
				advertisement.setCounter(advertisement.getCounter()+1);
			}
			advertisementMapper.updateBatch(list);
		}
		return 0;
	}

	protected List<Advertisement> convertList(List<Advertisement> list) {
		if(list == null || list.size()==0) return list;
		Map<Integer, Advertiser> map = advertiserMapper.selectAllMap();
		Advertiser ader = null;
		for (Advertisement advertisement : list) {
			ader = map.get(advertisement.getAdv_id());
			advertisement.setAderName(ader.getName());
			advertisement.setAderType(ader.getAdvType());
		}
		return list;
	}
}
